local meta = FindMetaTable( "Player" )
if !meta then error( "NO FUCKING META TABLE!!!" ) end

function meta:Cloak()

	if self:Team() == TEAM_HIDE then
		self.IsCloaked = true
		self.TargetAlpha = 15		
	end
	
end

function meta:UnCloak()

	self.IsCloaked = false
	self.TargetAlpha = 255		
	
end

function GM:PlayerInitialSpawn( ply )
	
	ply.IsCloaked = false
	ply.TargetAlpha = 255
	
end

-- Helper function to set a players alpha.
function updatePlayerAlpha( ply, alpha )

	if ply.Alpha != alpha then

		if ply:Team() ~= TEAM_HIDE then return false end

		-- Cloak the players world model.
		wepWorldModel = ply:GetActiveWeapon()
		if !wepWorldModel || !wepWorldModel:IsValid() then
			print( "ERROR: Weapon entity not found!" )
		else
			wepWorldModel:SetColor( 255, 255, 255, alpha )
		end
		
		ply:SetColor( 255, 255, 255, alpha )

		-- Set the current alpha
		ply.Alpha = alpha

	end
	
end

function syncClients()

	for k, ply in pairs( player.GetAll() ) do
			
		umsg.Start( "CloakSync", ply )
			umsg.Bool( ply.IsCloaked || false )
			umsg.Short( ply.Alpha || 255 )
			umsg.Short( ply.TargetAlpha || 255 )
		umsg.End()
	
	end

end
timer.Create( "CloakUpdate", 10, 0, syncClients )

-- Ditching the player alpha increases when moving idea.
function cloakThink()

	for k, ply in pairs( player.GetAll() ) do

		-- Do the actual calculations.
		if ply.TargetAlpha && ply:Team() == TEAM_HIDE then
			
			local newAlpha
			
			if ply.Alpha && ply.Alpha ~= ply.TargetAlpha then
					
				newAlpha = math.Approach( ply.Alpha, ply.TargetAlpha, 20 ) 

			else
			
				-- there is no alpha value set, should just go straight to the target.
				newAlpha = ply.TargetAlpha
				
			end
			
			-- Do it!
			updatePlayerAlpha( ply, newAlpha )
		
		else
		
			updatePlayerAlpha( ply, 255 )
		
		end
		
	end
	
end
timer.Create( "cloakThink", 0.1, 0, cloakThink )





